import React, { useContext, useMemo, useReducer, useRef } from 'react'
import RenderPhotoListDrawer from '@/views/productManagement/components/insideRework/photoModule'
import { Button, Card, Input, notification } from 'antd'
import { ScanOutlined, BarcodeOutlined } from '@ant-design/icons'
import RenderProductTable, { ProductInfo } from '@/views/productManagement/components/insideRework/productModule'
import { ScanCode } from '@/api/rework'
import { ERR_OK, isObject } from '@/utils/commons'
import { isEqual } from 'lodash'

const initStoreState = {
  // productList: [],  //  全部的产品列表 [{}]
  product: {},
  barcode: '',  //  用户输入的barcode  OF0001352853
  drawerVisible: false, //  照片选择配置列表 drawer
  selectPartId: '', // 用于展示drawer
  // prodIds: {} //  日后考虑保存的扩展
  // reworkReasonFrom: []  //  返工原因的表格

  partsSelectPhotos: {} //  {partId:[]  // part select photos }

}

const noop = () => {

}

export const ProductStoreContext = React.createContext({ state: initStoreState, dispatch: noop })

const scanTips = '请让鼠标光标集中在这里之后再来使用扫码枪扫瞄'

//  头部的条码扫描框
function RenderHeader() {
  const { state, dispatch } = useContext(ProductStoreContext)

  const getOrderData = async(barcode) => {
    try {
      const { Code, Result, Message } =
        await ScanCode({ code: barcode })
      // await import('./mock.json')
      if (Code === ERR_OK) {
        notification.success({ message: '扫描条码成功.' })
        return Result
      }
    } catch (e) {
      console.log(e)
      notification.warning({ message: e })
    }
  }
  const { barcode } = state
  const getData = async() => {
    // if (isEqual()){
    //   notification.warning({ message: '两次输入代码一致'})
    //   return
    // }
    if (!barcode) {
      return notification.warning({ message: '条码格式不合法' })
    }
    dispatch({ type: 'scanBarcode', orderData: await getOrderData(barcode) })
  }

  const scanInput = useRef(null)

  const nextScan = () => {
    scanInput.current['focus']()
  }

  return useMemo(() => <div style={{ marginBottom: 20, display: 'flex', justifyContent: 'center' }}>
    <Input
      size={'large'}
      ref={scanInput}
      value={barcode}
      addonBefore={<BarcodeOutlined onClick={nextScan}/>}
      style={{ width: 510 }}
      autoFocus
      placeholder={scanTips}
      onPressEnter={_ => getData()}
      onChange={({ target: { value: barcode } }) =>
        dispatch({ type: 'barcodeChange', barcode })}/>
    <Button size={'large'} type={'primary'} onClick={nextScan} icon={<ScanOutlined/>}>开始扫描</Button>
  </div>, [state.barcode, dispatch])
}

// const ca = (actions) => {
//   if (!Array.isArray(actions)) {
//     return {}
//   }
//   if (actions.length === 0) {
//     return {}
//   }
//   return actions.reduce((acc, cur) => ({ ...acc, [cur]: cur }), {})
// }

//  redux store
const storeReducer = (state, { type, ...payload }) => {
  const conditions = {
    // reworkReasonFromChange() {
    //   const { allFields, changedFields } = payload
    //   console.log(allFields, changedFields)
    //   return { ...state, reworkReasonFrom: allFields }
    // },
    removeCurSelectPhotos: () => {
      // const { photos } = payload
      const { selectPartId: OrderProductPartID, partsSelectPhotos, product } = state
      return {
        ...state, product: {
          ...product, partEntries: {
            ...product.partEntries,
            [OrderProductPartID]: product.partEntries[OrderProductPartID].filter((e) => {
              return partsSelectPhotos[OrderProductPartID].includes(i => e['OrderFileId'] !== i)
            })
          }
        }
      }
    },
    changePartsSelectPhotos() {
      const { photoIds } = payload
      //  OrderFileId
      const { selectPartId, partsSelectPhotos } = state
      return {
        ...state, partsSelectPhotos: { ...state.partsSelectPhotos, [selectPartId]: photoIds }
      }
    },
    changeCurrentComp: () => {
      const { OrderProductPartId } = payload
      return { ...state, selectPartId: OrderProductPartId }
    },
    compDetailDrawerToggle: () => {
      const { drawerVisible } = state
      return { ...state, drawerVisible: !drawerVisible }
    },
    barcodeChange: () => {
      console.log(payload)
      const { barcode } = payload
      return { ...state, barcode }
    },
    scanBarcode() {
      //  拍平数据,
      const normalizeData = (orderData) => {
        try {
          const { Product, OrderProductParts, ...restOrderData } = orderData
          // const normalizeRoutes = (OrderTechRoutes) => {
          // }
          const normalizeFiles = (OrderFiles) => {
            return OrderFiles.reduce((acc, cur) => {
              const { OrderFileId } = cur
              return {
                ...acc, fileEntries: { ...acc.fileEntries, [OrderFileId]: cur },
                fileIds: acc.fileIds.concat(OrderFileId)
              }
            }, { fileEntries: {}, fileIds: [] })
          }
          // normalize component
          const normalizeComponents = OrderProductParts.reduce((acc, component) => {
            const { OrderProductPartId, OrderFiles, OrderTechRoutes, ...restCompData } = component
            // const { routeEntries, routeIds } = normalizeRoutes(OrderTechRoutes)
            const { fileEntries, fileIds } = normalizeFiles(OrderFiles)
            return {
              ...acc,
              partEntries: {
                ...acc.partEntries,
                [OrderProductPartId]: { ...restCompData, OrderProductPartId, fileIds, OrderTechRoutes }
              },
              fileEntries,
              partIds: acc.partIds.concat(OrderProductPartId)
              // routeEntries:{...acc.routeEntries,routeEntries},
            }
          }, {
            partEntries: {},
            fileEntries: {},
            partIds: []
            // routeEntries: {},
          })
          return {
            ...Product, ...restOrderData, ...normalizeComponents
          }
        } catch (e) {
          console.log('error %o', e)
          notification.warning({ message: '格式化数据对象失败!' })
        }
      }

      //  返回合并后的对象
      const groupData = (productList, orderData) => {
        console.log('orderData %o', productList)
        console.log('orderData %o', orderData)
        if (productList.length === 0) {
          return [orderData]
        }
        const { OrderProductId } = orderData
        const prod = state.productList.find(v => v.OrderProductId === OrderProductId)
        if (!prod) {
          return [...productList, prod]
        }

        //  prod.partIds, orderData.partIds
        if (prod.partIds) {
          // 只考虑新增了组件的情况,如果
        }
        //  新增组件中的照片

        //  两边都是格式化之后的数据
        //  merge update data
        return []
      }
      const { orderData } = payload
      console.log(orderData)

      if (!isObject(orderData)) {
        return { ...state, product: {}, barcode: '' }
      }

      const product = orderData|>  normalizeData
      console.log(product)

      // |> (_ => groupData(state.productList, _))
      // return {
      //   ...state, productList: ret
      // }
      return { ...state, product, barcode: '' }
    }
  }
  const match = conditions[type]
  return match ? match() : state
}

export default function Main() {
  const [state, dispatch] = useReducer(storeReducer, initStoreState)

  return <React.Fragment>
    <ProductStoreContext.Provider value={{ state, dispatch }}>
      <div style={{ margin: 20 }}>
        <RenderHeader/>
        <ProductInfo/>
        {Boolean(state.product.partEntries) && <RenderProductTable/>}
      </div>
      <RenderPhotoListDrawer/>
    </ProductStoreContext.Provider>
  </React.Fragment>
}
